import axios from 'axios'
import qs from "qs";
/**
 * 请求拦截判断登录状态是否过期
 */
const getToken = () => {
    let token = ''
    if (localStorage.getItem("userData")) {
        token = JSON.parse(localStorage.getItem("userData")).auth_token
    }
    return token
}
//加法函数
const accAdd = function (arg1, arg2) {
    var r1, r2, m;
    try {
        r1 = arg1.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg2.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (arg1 * m + arg2 * m) / m;
}
//乘法函数
const accMul = function (arg1, arg2) {
    var m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += s1.split(".")[1].length;
    } catch (e) { }
    try {
        m += s2.split(".")[1].length;
    } catch (e) { }
    return (
        Number(s1.replace(".", "")) *
        Number(s2.replace(".", "")) /
        Math.pow(10, m)
    );
}
//减法函数
const Subtr = function (arg1, arg2) {
    var r1, r2, m, n;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    //last modify by deeka
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
/**
 * 打开webview
 */
const openWindow = (url, title, extras, back) => {
    mui.openWindow({
        id: url,
        url: url,
        styles: {
            titleNView: {
                autoBackButton: back || 'true',
                titleText: title,
                backgroundColor: '#bc2923',
                titleColor: '#fff'
            }
        },
        extras: extras || {}
    })
}
/**
 * 请求配置
 */
axios.defaults.baseURL = 'http://192.168.1.236/index.php/app/home'
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
axios.interceptors.request.use(config => {
    if (typeof plus != 'undefined') plus.nativeUI.showWaiting()
    //添加token
    if (config.method == 'post') {
        config.data = qs.stringify({
            ...config.data,
            auth_token: getToken()
        })
    }
    if (config.method == 'get') {
        config.params = {
            ...config.params,
            auth_token: getToken()
        }
    }
    return config
})
axios.interceptors.response.use(res => {
    if (typeof plus != 'undefined') plus.nativeUI.closeWaiting()
    //未登录跳转登录页面
    if (res.data.code == '-6') {
        // localStorage.clear()
        mui.toast(res.data.msg);
        setTimeout(() => {
            openWindow('login.html', '登录', {}, 'false')
        }, 2000);
    }
    return res
})
export { axios, openWindow, accAdd, accMul, Subtr }